package com.travelDevelop.iterceptor;

import java.util.HashSet;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.travelDevelop.commons.bean.User;
import com.travelDevelop.commons.util.WebConst;
import com.travelDevelop.service.PermissionService;

public class AuthInterceptor extends HandlerInterceptorAdapter {

	private static final Logger logger = LogManager.getLogger(AuthInterceptor.class);

	@Autowired
	PermissionService permissionService;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		
		String requestUrl = request.getRequestURI();
		if (requestUrl.equals("/index") ||requestUrl.equals("/login/checkToken") ||requestUrl.equals("/login") || requestUrl.equals("/login/login") ||  requestUrl.equals("/sysfile/download") ||  requestUrl.equals("/login/getVC") || requestUrl.equals("/CC/login")|| requestUrl.equals("/login/check")) {
			return true;
		}

		HttpSession session = request.getSession();
		User user = (User) session.getAttribute(WebConst.SESSION_LOGIN_USER);
		if (user == null) {
			response.sendRedirect("/index");
			return false;
		}

		if (WebConst.isDebug || user.getUsername().equals(WebConst.ROOT_USER_NAME)) {
			return true;
		}

		if (handler.getClass().isAssignableFrom(HandlerMethod.class)) {
			HandlerMethod handlerMethod = (HandlerMethod) handler;
			Object obj = handlerMethod.getBean();
			Auth authBean = obj.getClass().getAnnotation(Auth.class);
			Auth authMethod = handlerMethod.getMethodAnnotation(Auth.class);
			// 没有声明需要权限,或者声明不验证权限
			if (authMethod == null && authBean == null)
				return true;
			else {
				Set<String> set = new HashSet<String>();
				if (authMethod != null) {
					String[] operationMethod = authMethod.operation();
					for (int i = 0; i < operationMethod.length; i++) {
						set.add(operationMethod[i]);
					}
				}
				if (authBean != null) {
					String[] operationBean = authBean.operation();
					for (int i = 0; i < operationBean.length; i++) {
						set.add(operationBean[i]);
					}
				}

				if (!permissionService.hasPermission(user.getId(), set)) {
					response.sendRedirect("/error/noPermission");
					return false;
				}
				return true;
			}
		} else {
			return true;
		}
	}

	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		if(ex!=null){
			logger.error(ex.getMessage(),ex);
		}
	}
}
